package main

import (
	"context"
	"fmt"
	examplePb "grpc-server/grpc-protocol/example"
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {

	// 连接配置
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithBlock(),
	}

	// 开始请求服务端
	conn, err := grpc.Dial("192.168.1.10:50051", opts...)
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	// 请求结束后就自动关闭连接
	defer func(conn *grpc.ClientConn) {
		err := conn.Close()
		if err != nil {
			panic(err)
		}
	}(conn)

	// Contact the server and print out its response.
	//name := defaultName
	//if len(os.Args) > 1 {
	//   name = os.Args[1]
	//}

	// 创建一个子节点的context,1秒后自动超时
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	c := examplePb.NewGreeterClient(conn)

	req := examplePb.HelloRequest{
		Name: "看看请求",
	}

	rsp, err := c.SayHello(ctx, &req)
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}

	fmt.Println(rsp)
}
